<script setup>
import { ref, onMounted } from 'vue'
import { 
  queryPageApi, 
  addApi, 
  queryByIdApi, 
  updateApi, 
  deleteApi 
} from "@/api/activity";
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义数据模型
const activityList = ref([])
const total = ref(0)
const loading = ref(false)
const searchForm = ref({
  channel: '',
  type: '',
  status: '',
  page: 1,
  pageSize: 10
})

// 获取活动列表
const getActivityList = async () => {
  try {
    loading.value = true
    const response = await queryPageApi(searchForm.value)
    if (response.code === 1) {
      activityList.value = response.data.rows || []
      total.value = response.data.total || 0
    } else {
      activityList.value = []
      total.value = 0
      ElMessage.error(response.msg)
    }
  } catch (error) {
    activityList.value = []
    total.value = 0
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时调用
onMounted(() => {
  getActivityList()
})

// 分页处理
const handleSizeChange = (pageSize) => {
  searchForm.value.pageSize = pageSize
  getActivityList()
}

const handleCurrentChange = (currentPage) => {
  searchForm.value.page = currentPage
  getActivityList()
}

// 清空搜索条件
const resetSearch = () => {
  searchForm.value = {
    channel: '',
    type: '',
    status: '',
    page: 1,
    pageSize: 10
  }
  getActivityList()
}

// 创建活动对话框相关
const dialogFormVisible = ref(false)
const formTitle = ref('')
const activity = ref({
  name: '',
  channel: '',
  type: '',
  discount: null,
  voucher: null,
  startTime: '',
  endTime: '',
  description: ''
})
const rules = ref({
  name: [
    { required: true, message: '活动名称为必填项', trigger: 'blur' },
    { min: 1, max: 20, message: '活动名称应该在1-20位之间', trigger: 'blur' }
  ],
  channel: [{ required: true, message: '渠道来源为必填项', trigger: 'change' }],
  type: [{ required: true, message: '活动类型为必填项', trigger: 'change' }],
  startTime: [{ required: true, message: '开始时间为必填项', trigger: 'change' }],
  endTime: [{ required: true, message: '结束时间为必填项', trigger: 'change' }],
  description: [
    { required: true, message: '活动简介为必填项', trigger: 'blur' },
    { min: 5, max: 100, message: '活动简介应该在5-100位之间', trigger: 'blur' }
  ]
})

const activityFormRef = ref(null)

const handleAdd = () => {
  dialogFormVisible.value = true
  formTitle.value = '创建活动'
  activity.value = {
    name: '',
    channel: '',
    type: '',
    discount: null,
    voucher: null,
    startTime: '',
    endTime: '',
    description: ''
  }
  if (activityFormRef.value) {
    activityFormRef.value.resetFields()
  }
}

const save = async () => {
  activityFormRef.value.validate(async (valid) => {
    if (valid) {
      let result
      if (activity.value.id) {
        result = await updateApi(activity.value)
      } else {
        result = await addApi(activity.value)
      }

      if (result.code === 1) {
        ElMessage.success('保存成功')
        dialogFormVisible.value = false
        getActivityList()
      } else {
        ElMessage.error(result.msg)
      }
    } else {
      ElMessage.error('请填写正确的信息')
    }
  })
}

const handleEdit = async (id) => {
  const result = await queryByIdApi(id)
  if (result.data.code ) {
    dialogFormVisible.value = true
    formTitle.value = '修改活动'
    activity.value = result.data
    if (activityFormRef.value) {
      activityFormRef.value.resetFields()
    }
  } else {
    ElMessage.error(result.msg)
  }
}

const handleDelete = async (id) => {
  ElMessageBox.confirm('您确认要删除该活动吗', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const result = await deleteApi(id)
    if (result.code === 1) {
      ElMessage.success('删除成功')
      getActivityList()
    } else {
      ElMessage.error(result.msg)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
</script>

<template>
  <div class="activity-page">
    <!-- 顶部标题和操作 -->
    <div class="activity-header">
      <div>
        <h2 class="activity-title">
          <el-icon><Collection /></el-icon> 活动管理
        </h2>
        <div class="activity-desc">
          高效管理平台活动资源，支持新增、编辑、删除和状态切换。
        </div>
      </div>
      <el-button type="primary" @click="handleAdd" class="add-btn" size="large"
        ><el-icon><Plus /></el-icon>添加活动</el-button
      >
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="18" class="activity-stats">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card stat-blue">
          <div class="stat-icon">
            <el-icon><Collection /></el-icon>
          </div>
          <div>
            <div class="stat-value">{{ total }}</div>
            <div class="stat-label">活动总数</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card stat-green">
          <div class="stat-icon">
            <el-icon><CircleCheckFilled /></el-icon>
          </div>
          <div>
            <div class="stat-value">
              {{ activityList.filter((a) => a.status === 1).length }}
            </div>
            <div class="stat-label">进行中</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card stat-red">
          <div class="stat-icon">
            <el-icon><CircleCloseFilled /></el-icon>
          </div>
          <div>
            <div class="stat-value">
              {{ activityList.filter((a) => a.status === 0).length }}
            </div>
            <div class="stat-label">已结束</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card stat-yellow">
          <div class="stat-icon">
            <el-icon><Timer /></el-icon>
          </div>
          <div>
            <div class="stat-value">
              {{
                activityList.length > 0
                  ? activityList[0].updateTime?.slice(0, 10)
                  : "--"
              }}
            </div>
            <div class="stat-label">最近更新时间</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 卡片化表格区域 -->
    <el-card class="activity-table-card">
      <template #header>
        <div class="table-header-flex">
          <div class="table-title">
            <el-icon><List /></el-icon> 活动列表
          </div>
          <el-form
            :inline="true"
            :model="searchForm"
            ref="queryForm"
            class="search-form"
          >
            <el-form-item label="渠道来源">
              <el-select
                v-model="searchForm.channel"
                placeholder="请选择"
                clearable
                size="small"
                style="width: 120px"
              >
                <el-option label="线上活动" value="1" />
                <el-option label="推广介绍" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="活动类型">
              <el-select
                v-model="searchForm.type"
                placeholder="请选择"
                clearable
                size="small"
                style="width: 120px"
              >
                <el-option label="课程折扣" value="1" />
                <el-option label="代金券" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="活动状态">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择"
                clearable
                size="small"
                style="width: 120px"
              >
                <el-option label="进行中" value="1" />
                <el-option label="已结束" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getActivityList" size="small"
                ><el-icon><Search /></el-icon>搜索</el-button
              >
              <el-button @click="resetSearch" size="small"
                ><el-icon><Refresh /></el-icon>清空</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </template>
      <el-table :data="activityList" border stripe class="activity-table" size="small" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="name"
          label="活动名称"
          min-width="160"
          align="center"
        >
          <template #default="scope">
            <el-icon class="activity-table-icon"><Collection /></el-icon>
            <span class="activity-name">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="channel"
          label="渠道来源"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.channel === '1' ? 'primary' : 'success'"
              size="small"
            >
              <el-icon style="vertical-align: middle">
                <PriceTag />
              </el-icon>
              {{ scope.row.channel === '1' ? "线上活动" : "推广介绍" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="type"
          label="活动类型"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.type === '1' ? 'warning' : 'danger'"
              size="small"
            >
              {{ scope.row.type === '1' ? "课程折扣" : "代金券" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="startTime"
          label="开始时间"
          min-width="140"
          align="center"
        />
        <el-table-column
          prop="endTime"
          label="结束时间"
          min-width="140"
          align="center"
        />
        <el-table-column
          prop="updateTime"
          label="最后修改时间"
          min-width="140"
          align="center"
        />
        <el-table-column label="操作" align="center" min-width="120">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row.id)">
              <el-icon><Edit /></el-icon>修改
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          small
        />
      </div>
    </el-card>

    <!-- 添加/编辑活动对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="formTitle"
      width="420"
      class="activity-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        :model="activity"
        :rules="rules"
        ref="activityFormRef"
        label-width="90px"
        class="activity-form"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input
            v-model="activity.name"
            autocomplete="off"
            placeholder="请输入活动名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="渠道来源" prop="channel">
          <el-select v-model="activity.channel" placeholder="请选择">
            <el-option label="线上活动" value="1" />
            <el-option label="推广介绍" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="activity.type" placeholder="请选择">
            <el-option label="课程折扣" value="1" />
            <el-option label="代金券" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动折扣" v-if="activity.type === '1'" prop="discount">
          <el-input v-model="activity.discount" placeholder="请输入折扣（如：8.8）"></el-input>
        </el-form-item>
        <el-form-item label="代金券金额" v-if="activity.type === '2'" prop="voucher">
          <el-input v-model="activity.voucher" placeholder="请输入代金券金额（如：500）"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="activity.startTime" type="datetime" placeholder="选择开始时间" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="activity.endTime" type="datetime" placeholder="选择结束时间" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="活动简介" prop="description">
          <el-input v-model="activity.description" type="textarea" placeholder="请输入活动简介" maxlength="100" show-word-limit :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.activity-container {
  padding: 20px;
  max-width: 100%;
}

.demo-form-inline {
  margin-bottom: 20px;
}

.demo-form-inline .el-form-item {
  margin-right: 20px;
}

.demo-form-inline .el-form-item__label {
  width: auto;
}

.el-table {
  margin-bottom: 20px;
  width: 100%;
}

.el-pagination {
  display: flex;
  justify-content: flex-end;
}

.activity-page {
  padding: 18px 10px 30px 10px;
  background: #f5f7fa;
  min-height: 100vh;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 18px;
  gap: 12px;
  flex-wrap: wrap;
}

.activity-title {
  font-size: 28px;
  font-weight: 800;
  background: linear-gradient(90deg, #409eff, #64b5f6);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.activity-desc {
  color: #909399;
  font-size: 15px;
  margin-bottom: 2px;
}

.activity-stats {
  margin-bottom: 18px;
}

.stat-card {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #e6f7ff33;
  padding: 18px 16px;
  margin-bottom: 10px;
  min-height: 80px;
  gap: 16px;
}

.stat-icon {
  font-size: 32px;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin-right: 8px;
}

.stat-blue {
  background: linear-gradient(90deg, #e6f7ff, #f0faff);
  color: #1890ff;
}

.stat-green {
  background: linear-gradient(90deg, #e6ffed, #f6fffa);
  color: #52c41a;
}

.stat-red {
  background: linear-gradient(90deg, #fff1f0, #fff7f6);
  color: #ff4d4f;
}

.stat-yellow {
  background: linear-gradient(90deg, #fffbe6, #fffef6);
  color: #faad14;
}

.stat-value {
  font-size: 22px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.activity-table-card {
  margin-top: 8px;
  border-radius: 12px;
  box-shadow: 0 2px 8px #e6f7ff33;
  background: #fff;
}

.table-header-flex {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
  display: flex;
  align-items: center;
  gap: 6px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 0;
}

.activity-table {
  border-radius: 8px;
  overflow: hidden;
  font-size: 15px;
  background: #fff;
  width: 100%;
}

.activity-table-icon {
  color: #409eff;
  margin-right: 6px;
  font-size: 18px;
}

.activity-name {
  font-weight: 500;
  color: #333;
}

.pagination {
  margin-top: 18px;
  display: flex;
  justify-content: flex-end;
}

.activity-dialog :deep(.el-dialog__body) {
  padding-top: 24px;
}

.activity-form {
  padding: 0 8px;
}

.dialog-footer {
  text-align: right;
}

@media (max-width: 900px) {
  .activity-header,
  .table-header-flex {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .stat-card {
    margin-bottom: 10px;
  }
}
</style>